package com.leoly.fullnexus4.views;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.ImageView;

import com.leoly.fullnexus4.services.OnMoveListener;
import com.leoly.fullnexus4.utils.TopConstants;

/**
 * @author <a href="mailto:kris@krislq.com">Kris.lee</a>
 * @website www.krislq.com
 * @date Nov 29, 2012
 * @version 1.0.0
 */
public class FloatView extends ImageView {
	private float mTouchX;

	private float mTouchY;

	private float x;

	private float y;

	private float mStartX;

	private float mStartY;

	private OnClickListener mClickListener;

	private OnMoveListener mMoveListener;

	private boolean isMove = false;

	private WindowManager windowManager = (WindowManager) getContext()
			.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);

	private WindowManager.LayoutParams windowManagerParams = ((FloatApplication) getContext()
			.getApplicationContext()).getWindowParams();

	private Handler handler = ((FloatApplication) getContext()
			.getApplicationContext()).getHandler();

	public FloatView(Context context) {
		super(context);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Rect frame = new Rect();
		getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;
		x = event.getRawX();
		y = event.getRawY() - statusBarHeight;
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			Bundle bundle = new Bundle();
			bundle.putBoolean(TopConstants.HANDLER_TAG, false);
			Message msg = new Message();
			msg.setData(bundle);
			handler.sendMessage(msg);
			mTouchX = event.getX();
			mTouchY = event.getY();
			mStartX = x;
			mStartY = y;
			break;

		case MotionEvent.ACTION_MOVE:
			updateViewPosition();
			isMove = true;
			break;

		case MotionEvent.ACTION_UP:
			mTouchX = mTouchY = 0;
			if (Math.abs(x - mStartX) < 25 && Math.abs(y - mStartY) < 25) {
				if (mClickListener != null) {
					isMove = false;
					mClickListener.onClick(this);
				}
			}

			Log.i(TopConstants.APP_TAG,
					Math.abs(x - mStartX) + "-----" + Math.abs(y - mStartY));
			if (isMove
					&& (Math.abs(x - mStartX) < 200 && Math.abs(y - mStartY) < 200)) {
				this.mMoveListener.onMove();
			}
			break;
		}
		return true;
	}

	public void setOnMoveListener(OnMoveListener mMoveListener) {
		this.mMoveListener = mMoveListener;
	}

	@Override
	public void setOnClickListener(OnClickListener l) {
		this.mClickListener = l;
	}

	private void updateViewPosition() {
		windowManagerParams.x = (int) (x - mTouchX);
		windowManagerParams.y = (int) (y - mTouchY);
		windowManager.updateViewLayout(this, windowManagerParams);
	}
}
